/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
// 自定义6字节音符数据结构 (4字节时间 + 1字节音符 + 1字节力度/类型)
typedef struct {
    uint32_t time;    // 时间戳(毫秒)
    uint8_t note;     // 音符编号
    uint8_t velocity_type; // 高7位:力度, 最低位:类型(1=开始,0=结束)
} NoteData;

// 接收缓冲区
#define RX_BUFFER_SIZE 6  // 精确匹配一个音符数据包大小
uint8_t rxBuffer[RX_BUFFER_SIZE];
uint16_t rxBufferIndex = 0;
uint16_t rxBufferLength = 0;

// 当前解析位置
uint16_t parsePosition = 0;

// 当前活动音符
uint8_t activeNote = 0xFF;

// MIDI音符频率表（Hz）- 从C0到B8
const uint16_t noteFrequency[] = {
    16, 17, 18, 19, 21, 22, 23, 25, 26, 28, 29, 31,  // C0 to B0
    33, 35, 37, 39, 41, 44, 46, 49, 52, 55, 58, 62,  // C1 to B1
    65, 69, 73, 78, 82, 87, 93, 98, 104, 110, 117, 123,  // C2 to B2
    131, 139, 147, 156, 165, 175, 185, 196, 208, 220, 233, 247,  // C3 to B3
    262, 277, 294, 311, 330, 349, 370, 392, 415, 440, 466, 494,  // C4 to B4
    523, 554, 587, 622, 659, 698, 740, 784, 831, 880, 932, 988,  // C5 to B5
    1047, 1109, 1175, 1245, 1319, 1397, 1480, 1568, 1661, 1760, 1865, 1976,  // C6 to B6
    2093, 2217, 2349, 2489, 2637, 2794, 2960, 3136, 3322, 3520, 3729, 3951,  // C7 to B7
    4186, 4435, 4699, 4978, 5274, 5588, 5920, 6272, 6645, 7040, 7459, 7902   // C8 to B8
};
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
// 设置PWM频率
void setPWMFrequency(uint16_t frequency) {
    if (frequency == 0) {
        // 停止输出
        HAL_TIM_PWM_Stop(&htim2, TIM_CHANNEL_1);
        return;
    }
    
    // 计算定时器参数
    uint32_t timer_clock = 72000000; // APB1 timer clock = 72MHz
    uint32_t prescaler = 72;         // Fixed prescaler to get 1MHz timer clock
    uint32_t period = (timer_clock / prescaler) / frequency - 1;
    
    // 更新定时器参数
    __HAL_TIM_SET_AUTORELOAD(&htim2, period);
    __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, period / 2); // 50% duty cycle
    
    // 确保PWM输出已启动
    HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);
}

// 发送确认消息
void sendAck(uint8_t status, uint8_t data1, uint8_t data2) {
    char ackMsg[32];
    // 格式化为文本: "ACK:status,data1,data2\n"
    int len = sprintf(ackMsg, "ACK:%d,%d,%d\n", status, data1, data2);
    // 使用非阻塞方式发送，避免在中断中长时间等待
    HAL_UART_Transmit_IT(&huart1, (uint8_t*)ackMsg, len);
}

// 处理MIDI消息
void handleMIDIMessage(uint8_t status, uint8_t data1, uint8_t data2) {
    uint8_t messageType = status & 0xF0;
    uint8_t channel = status & 0x0F;
    
    // 只处理通道1-16的消息
    if (channel > 15) {
        return;
    }
    
    switch(messageType) {
        case 0x90: // Note On
            if (data2 > 0) { // Note On with velocity > 0
                if (data1 < sizeof(noteFrequency)/sizeof(noteFrequency[0])) {
                    setPWMFrequency(noteFrequency[data1]);
                    activeNote = data1;
                }
                break;
            }
            // If velocity = 0, treat as Note Off
            // fall through
        case 0x80: // Note Off
            if (activeNote == data1) {
                setPWMFrequency(0); // Stop the sound
                activeNote = 0xFF;
            }
            break;
        default:
            // 忽略其他类型的MIDI消息
            break;
    }
    
    // 发送确认消息
    sendAck(status, data1, data2);
}

// 处理接收缓冲区中的音符数据
void processNoteData(void) {
    // 检查是否有足够数据解析(至少6字节)
    while (parsePosition + 6 <= rxBufferLength) {
        NoteData note;
        
        // 解析4字节时间戳(大端序)
        note.time = (rxBuffer[parsePosition] << 24) | 
                   (rxBuffer[parsePosition+1] << 16) |
                   (rxBuffer[parsePosition+2] << 8) |
                   rxBuffer[parsePosition+3];
        parsePosition += 4;
        
        // 解析音符和力度/类型
        note.note = rxBuffer[parsePosition++];
        note.velocity_type = rxBuffer[parsePosition++];
        
        // 处理音符
        uint8_t velocity = note.velocity_type >> 1;
        uint8_t type = note.velocity_type & 0x01;
        
        // 模拟MIDI消息: 0x90=Note On, 0x80=Note Off
        handleMIDIMessage(type ? 0x90 : 0x80, note.note, velocity);
    }
    
    // 移动剩余数据到缓冲区开头
    if (parsePosition > 0) {
        uint16_t remaining = rxBufferLength - parsePosition;
        if (remaining > 0) {
            memmove(rxBuffer, rxBuffer + parsePosition, remaining);
        }
        rxBufferLength = remaining;
        parsePosition = 0;
    }
}

// UART接收回调
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
    if (huart->Instance == USART1) {
        // 更新接收到的数据长度
        rxBufferLength = RX_BUFFER_SIZE;
        parsePosition = 0;
        
        // 继续接收数据
        HAL_UART_Receive_IT(&huart1, rxBuffer, 6);
        
        // 处理接收到的数据
        processNoteData();
    }
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_TIM2_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */
// 初始化变量
  rxBufferLength = 0;
  parsePosition = 0;
  activeNote = 0xFF;
  
  // 调试输出初始化
  //printf("MIDI Player Ready\r\n");
  //printf("Waiting for 6-byte note data...\r\n");
  
  // 初始化PWM输出
  HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);
  
  // 设置初始频率为0（无声音）
  setPWMFrequency(0);
  
  // 发送启动确认消息
  const char* startMsg = "start\n";  // 添加换行符便于识别
  HAL_UART_Transmit_IT(&huart1, (uint8_t*)startMsg, strlen(startMsg));
  
  // 启动UART接收中断，使用多字节接收模式
  HAL_UART_Receive_IT(&huart1, rxBuffer, RX_BUFFER_SIZE);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    HAL_Delay(1000);
    HAL_GPIO_TogglePin(GPIOC,GPIO_PIN_13);
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
